package com.caixin.common.exception;

import com.caixin.common.response.ApiResult;
import com.caixin.common.response.CommonResultEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理类
 *
 * @author Administrator
 * @version 1.0.0
 * @createTime 2021年12月04日 17:23
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResult exceptionHandler(Exception e) {
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return ApiResult.fail(ex.getCommonResultEnum(), null);
        }
        if (e instanceof BindException) {
            BindException ex2 = (BindException) e;
            return ApiResult.fail(CommonResultEnum.VALIDATE.getCode(),
                    ex2.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        }
        if(e instanceof DomainValidException){
            DomainValidException ex = (DomainValidException) e;
            return ApiResult.fail(CommonResultEnum.VALIDATE.getCode(), ex.getMessage());
        }
        if(e instanceof IllegalArgumentException)
        {
            IllegalArgumentException ex = (IllegalArgumentException) e;
            return ApiResult.fail(CommonResultEnum.FAIL.getCode(), ex.getMessage());
        }
        return ApiResult.fail(CommonResultEnum.ERROR,null);
    }
}
